<template>
  <div>
    <div
        style="width: 1670px;min-height:770px;padding:24px 32px;margin:15px 0 15px 35px;
        border-radius: 26px;background-color: white">
      <div v-if="discussShow">
        <p style="margin: 0;font-size: 18px">讨论区</p>
        <el-button type="primary" @click="onDiscuss()" style="margin: 20px 0 0 20px">
          发起讨论
        </el-button>
        <el-divider></el-divider>
<!--        <div v-for="(item,index) in discussList" :id="index">-->
<!--          <el-link :href="'/#/learnEdit/forumindexEdit/'+item.courseId+'/'+item.discussId"-->
<!--                   style="font-size: 18px;margin:6px 6px" :underline="false">-->
<!--            {{ item.discussName }}-->
<!--          </el-link>-->
<!--          <p style="margin: 0;font-size: 14px">-->
<!--            <a style="color: #409EFF;cursor:pointer;">{{ item.userName }}</a>-->
<!--            <a style="margin-left: 8px">{{ item.createTime }}发表</a>-->
<!--          </p>-->
<!--          <p style="margin: 0 60px 0 0;text-align: right;font-size: 14px">-->
<!--            <a style="margin-right: 50px;">浏览：{{ item.browseNum }}</a><a>回复：{{ item.replyNum }}</a>-->
<!--          </p>-->
<!--          <el-divider></el-divider>-->
<!--        </div>-->
        <div v-for="(item,index) in discussList" :id="index">
          <p @click="toDiscuss(item.courseId,item.discussId)" style="font-size: 18px;margin:6px 6px;cursor:pointer">{{item.discussName}}</p>
          <div style="display: flex">
            <p style="width:50%;margin: 0;font-size: 14px">
              <a style="color: #409EFF;cursor:pointer;" @click="onUser(item.userId)">{{ item.userName }}</a>
              <a style="margin-left: 8px">{{ item.createTime|formatDate('yyyy-MM-dd HH:mm:ss') }}发表</a>
            </p>
            <p style="width:50%;;margin: 0 60px 0 0;text-align: right;font-size: 14px">
              <a style="margin-right: 50px;">浏览：{{ item.browseNum }}</a><a>回复：{{ item.replyNum }}</a>
            </p>
          </div>
          <el-divider></el-divider>
        </div>
        <el-pagination
            @size-change="handleSizeChangeDiscuss"
            @current-change="getPageDiscussByCourseId"
            :current-page="currentPage"
            :page-sizes="[10,15,20]"
            :page-size="pageSize"
            layout="total,sizes,prev,pager,next,jumper"
            :total="total"
            style="text-align: center;margin-top: 10px">
        </el-pagination>
        <el-dialog
            :visible.sync="discussVisible"
            width="40%"
            top="150px"
            center>
          <p style="width: 100%;font-size: 20px;color: #333333">发布讨论</p>
          <el-form :model="addDiscuss" :rules="rules" style="width: 75%;margin-left: 85px" ref="discussForm">
            <el-form-item label="讨论主题" prop="discussName">
              <el-input v-model="addDiscuss.discussName"></el-input>
            </el-form-item>
            <el-form-item label="讨论内容" prop="content">
              <div id="div1">
              </div>
            </el-form-item>
            <el-form-item style="text-align: center">
              <el-button type="primary" style="width: 100px;margin-left: 326px" @click="addOrUpdate('discussForm')">
                提交
              </el-button>
              <el-button style="width: 80px;margin-left: 10px" @click="">取消</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>
      </div>
      <div v-if="!discussShow">
        <p style="width: 1200px;margin: 20px 0 15px 10px">
          <el-breadcrumb separator=">">
            <el-breadcrumb-item :to="{ path: '/learnEdit/forumindexEdit/'+this.courseId }">讨论区</el-breadcrumb-item>
            <el-breadcrumb-item>主题详细</el-breadcrumb-item>
          </el-breadcrumb>
        </p>
        <el-divider></el-divider>
        <div style="width: 840px">
          <div style="padding:5px 20px 20px 20px;border-radius:16px;background-color: #F8F8F8">
            <p style="font-size: 20px;font-weight: bold">{{ discuss.discussName }}</p>
            <div v-html="this.discuss.content"></div>
            <p>{{ discuss.createTime|formatDate('yyyy-MM-dd HH:mm:ss') }}</p>
          </div>
          <p>共 {{ discuss.replyNum }} 条回复</p>
          <el-divider></el-divider>
          <div v-for="(item,index) in discussreplyList" v-if="item.discussId===discussId" :id="index">
            <div v-html="item.replyContent" style="font-size: 16px;margin:10px 6px">
            </div>
            <p style="margin: 0;font-size: 14px">
              <a style="color: #409EFF;cursor:pointer;" @click="onUser(item.userId)">{{ item.userName }}</a>
              <a style="margin-left: 8px">{{ item.createTime|formatDate('yyyy-MM-dd HH:mm:ss') }}发表</a>
            </p>
            <el-divider></el-divider>
          </div>
          <el-pagination
              v-if="total!==0"
              @size-change="handleSizeChangeDiscussReply"
              @current-change="getPageDiscussreply"
              :current-page="currentPage"
              :page-sizes="[10,15,20]"
              :page-size="pageSize"
              layout="total,sizes,prev,pager,next,jumper"
              :total="total"
              style="text-align: center;margin-top: 10px">
          </el-pagination>
          <el-form :model="addDiscussreply" :rules="rules" ref="discussReplyForm">
            <el-form-item label="回复内容" prop="replyContent">
              <div id="div1">
              </div>
            </el-form-item>
            <el-form-item style="text-align: right">
              <el-button type="primary" style="width: 100px;" @click="addOrUpdateReply('discussReplyForm')">发表回复
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import E from 'wangeditor'

export default {
  name: "ForumindexEditView",
  data() {
    return {
      editor: '',
      courseId: '',
      discussId: '',
      addDiscuss: {},
      addDiscussreply: {},
      discuss: {},
      discussList: [],
      discussreplyList: [],
      discussVisible: false,
      discussShow: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      rules: {
        discussName: {required: true, message: '讨论主题不能为空', trigger: 'blur'},
        content: {required: true, message: '讨论内容不能为空', trigger: 'blur'},
        replyContent: {required: true, message: '回复内容不能为空', trigger: 'blur'}
      }
    }
  },
  methods: {
    toDiscuss(courseId,discussId){
      this.addDiscussBrowseNum(discussId)
      this.$router.push({path: `/learnEdit/forumindexEdit/${courseId}/${discussId}`})
    },
    addDiscussBrowseNum(discussId){
      this.$axios({
        method: 'get',
        url: `http://localhost:8089/discuss/addBrowseNum/${discussId}`
      }).then(res => {
      }).catch(err => console.log(err));
    },
    // getDiscussByCourseId(courseId) {
    //   this.$axios({
    //     method: 'get',
    //     url: `http://localhost:8089/discuss/selectDiscussByCourseId/${courseId}`
    //   }).then(res => {
    //     this.discussList = res.data.dataobject;
    //   }).catch(err => console.log(err));
    // },
    handleSizeChangeDiscuss(size) {
      this.pageSize = size;
      this.getPageDiscussByCourseId(1);
    },
    getPageDiscussByCourseId(current = 1) {
      this.currentPage = current;
      this.$axios({
        method: 'get',
        url: `http://localhost:8089/course/getPageByCourseId/${this.currentPage}/${this.pageSize}/${this.courseId}`,
      }).then(res => {
        this.total = res.data.dataobject.total;
        this.discussList = res.data.dataobject.pageList;
      }).catch(err => console.log(err));
    },
    getDiscussById(discussId) {
      this.$axios({
        method: 'get',
        url: `http://localhost:8089/discuss/selectDiscussById/${discussId}`
      }).then(res => {
        if (res.data.code === 200)
          this.discuss = res.data.dataobject;
      }).catch(err => console.log(err));
    },
    // getDiscussreply(discussId) {
    //   this.$axios({
    //     method: 'get',
    //     url: `http://localhost:8089/discussreply/selectDiscussreplyByDiscussId/${discussId}`
    //   }).then(res => {
    //     if (res.data.code === 200)
    //       this.discussreplyList = res.data.dataobject;
    //   }).catch(err => console.log(err));
    // },
    handleSizeChangeDiscussReply(size) {
      this.pageSize = size;
      this.getPageDiscussreply(1);
    },
    getPageDiscussreply(current = 1) {
      this.currentPage = current;
      this.$axios({
        method: 'get',
        url: `http://localhost:8089/discussreply/getPageByDiscussId/${this.currentPage}/${this.pageSize}/${this.discussId}`,
      }).then(res => {
        this.total = res.data.dataobject.total;
        this.discussreplyList = res.data.dataobject.pageList;
      }).catch(err => console.log(err));
    },
    addDiscussStart() {
      this.$axios({
        method: 'post',
        url: "http://localhost:8089/discuss/createDiscuss",
        data: this.addDiscuss
      }).then(res => {
        if (res.data.code === 200) {
          this.$message.success("发起讨论成功");
          this.discussVisible = false;
          this.getDiscussByCourseId(this.courseId);
        } else
          this.$message.error("发起讨论失败")
      }).catch(err => console.log(err));
    },
    addDiscussreplyStart(){
      this.$axios({
        method: 'post',
        url: "http://localhost:8089/discussreply/createDiscussreply",
        data: this.addDiscussreply
      }).then(res => {
        if (res.data.code === 200) {
          this.$message.success("发表回复成功");
          this.discussVisible = false;
          this.getPageDiscussreply();
          this.getDiscussById(this.discussId);
          this.addDiscussreply.replyContent=''
          this.editor.txt.html('');
        } else
          this.$message.error("发表回复失败")
      }).catch(err => console.log(err));
    },
    //创建富文本编辑器，并进行上传图片、上传视颜的配置
    createRichTextEditor() {
      this.editor = new E('#div1');
      this.editor.config.uploadImgServer = 'http://localhost:8089/richText/uploadFile?type=img';
      this.editor.config.uploadFileName = 'file';
      this.editor.config.uploadVideoServer = 'http://localhost:8089/richText/uploadFile?type=video';
      this.editor.config.uploadVideoName = 'file';
      this.editor.config.placeholder = '请在此处填写内容';
      this.editor.create();
    },
    //确定按钮
    addOrUpdate(formName) {
      console.log(this.editor.txt.html());
      this.addDiscuss.content = this.editor.txt.html();
      this.addDiscuss.userId = localStorage.getItem('userId');
      this.addDiscuss.courseId = this.courseId;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.addDiscussStart();
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    addOrUpdateReply(formName) {
      console.log(this.editor.txt.html());
      this.addDiscussreply.replyContent = this.editor.txt.html();
      this.addDiscussreply.courseId=this.courseId;
      this.addDiscussreply.userId=localStorage.getItem('userId');
      this.addDiscussreply.discussId=this.discussId;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.addDiscussreplyStart();
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    onDiscuss() {
      if (this.$refs.discussForm!==undefined) {
        this.$nextTick(() => {
          this.$refs.discussForm.resetFields();
        });}
      this.discussVisible = true;
      this.$nextTick(() => {
        if (!this.editor) {
          this.createRichTextEditor();
        }
        this.editor.txt.html('');
      });
    },
    onUser(userId){
      this.$router.push({path:"/userHome/"+userId})
    }
  },
  filters:{
    formatDate: function(value,args) {
      var dt = new Date(value);
      if(args == 'yyyy年MM月dd日') {// yyyy年MM月dd日
        let year = dt.getFullYear();
        let month = (dt.getMonth() + 1).toString().padStart(2,'0');
        let date = dt.getDate().toString().padStart(2,'0');
        return `${year}年${month}月${date}日`;
      } else if(args == 'yyyy-MM-dd HH:mm:ss'){// yyyy-MM-dd HH:mm:ss
        let year = dt.getFullYear();
        let month = (dt.getMonth() + 1).toString().padStart(2,'0');
        let date = dt.getDate().toString().padStart(2,'0');
        let hour = dt.getHours().toString().padStart(2,'0');
        let minute = dt.getMinutes().toString().padStart(2,'0');
        let second = dt.getSeconds().toString().padStart(2,'0');
        return `${year}-${month}-${date} ${hour}:${minute}:${second}`;
      }
    }
  },
  created() {
    this.courseId = parseInt(this.$route.params.courseId);
    this.discussId = parseInt(this.$route.params.discussId);
    if (!this.discussId) {
      this.discussShow = true;
      this.getPageDiscussByCourseId();
    }
    else {
      this.getDiscussById(this.discussId);
      this.getPageDiscussreply();
    }
    // this.getDiscussreply(this.discussId);
    //this.getDiscussByCourseId(this.courseId);
    this.addDiscussreply={"replyContent":''};
    this.$nextTick(() => {
      if (!this.editor) {
        this.createRichTextEditor();
      }
      this.editor.txt.html('');
    });
  }
}
</script>

<style scoped>
/deep/ .el-divider {
  margin: 10px 0;
}
</style>